package com.shop.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.WeChatCart.UserCartRemoveDto;
import com.shop.entity.dto.WeChatCart.UserCartSaveDto;
import com.shop.entity.dto.WeChatCart.UserCartUpdateNumDto;
import com.shop.entity.pojo.Cart;
import com.shop.entity.pojo.Cost;
import com.shop.entity.pojo.Style;
import com.shop.entity.pojo.Wares;
import com.shop.entity.vo.CartVo;
import com.shop.user.mapper.CartMapper;
import com.shop.user.mapper.CostMapper;
import com.shop.user.mapper.StyleMapper;
import com.shop.user.mapper.WaresMapper;
import com.shop.user.service.CartService;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private WaresMapper waresMapper;
    @Autowired
    private StyleMapper styleMapper;
    @Autowired
    private CostMapper costMapper;

    @Override
    public Result addCart(UserCartSaveDto dto) {
        log.info("用户-添加购物车");
        long start = System.currentTimeMillis();
        if (dto==null||dto.getWaresId()==null||dto.getStyleId()==null||dto.getCostId()==null||dto.getWaresNumber()==Message.Check_Int_Null) {
            log.info("有参数为空，dto:{}",dto);
            return Result.errorResult(Code.PARAM_REQUIRE);
        }

        Long userId = BaseContext.getCurrentId();
        if (userId==null) {
            log.info("用户id为空");
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Cart cart=new Cart();
        Cart getCart = cartMapper.selectOne(Wrappers.<Cart>lambdaQuery()
                .eq(Cart::getUserId,userId)
                .eq(Cart::getWaresId,dto.getWaresId())
                .eq(Cart::getCostId,dto.getCostId()));
        if (getCart==null) {
            log.info("新增购物车数据");
            Wares wares = waresMapper.selectById(dto.getWaresId());
            Style style = styleMapper.selectById(dto.getStyleId());
            Cost cost = costMapper.selectById(dto.getCostId());
            if (wares==null||style==null||cost==null) {
                log.info("添加的物品不存在");
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }

            System.out.println(userId);
            cart.setUserId(userId);
            cart.setWaresName(wares.getWaresName());
            cart.setStyleName(style.getStyleName());
            cart.setCostPrice(cost.getWaresPrice());
            cart.setCostMessage(cost.getCostMessage());
            cart.setStyleImages(style.getStyleImages());
            cart.setWaresNumber(dto.getWaresNumber());
            cart.setWaresId(dto.getWaresId());
            cart.setStyleId(dto.getStyleId());
            cart.setCostId(dto.getCostId());
            int addCart = cartMapper.insert(cart);
            if (addCart==Message.Check_Int_False) {
                log.info("添加购物车失败");
                return Result.errorResult(Code.SERVER_ERROR);
            }
            return Result.okResult(Code.SUCCESS);
        }

        BeanUtils.copyProperties(getCart,cart);
        cart.setWaresNumber(cart.getWaresNumber()+dto.getWaresNumber());
        int updateCart = cartMapper.updateById(cart);
        if (updateCart==Message.Check_Int_False) {
            log.info("修改数量失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("用户添加商品到购物车进程完成，总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result<List<CartVo>> getCart() {
        log.info("用户-获取购物车列表");
        long start = System.currentTimeMillis();
        Long userId = BaseContext.getCurrentId();
        if (userId==null) {
            log.info("未接收到userId");
            return Result.errorResult(Code.NEED_LOGIN);
        }
//        String key=Message
        List<Cart> cart = cartMapper.selectList(Wrappers.<Cart>lambdaQuery().eq(Cart::getUserId,userId));
        long end = System.currentTimeMillis();
        log.info("用户在数据库中获取购物车列表数据进程完成，总耗时:{}",(end-start));
        return Result.okResult(cart);
    }

    @Override
    public Result updateCartNum(UserCartUpdateNumDto dto) {
        log.info("用户-修改购物车数量");
        long start = System.currentTimeMillis();

        if (dto==null||dto.getNewNumber()==null) {
            log.info("dto为空");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long userId = BaseContext.getCurrentId();
        if (userId==null) {
            log.info("未获取到userID");
            return Result.errorResult(Code.NEED_LOGIN);
        }
        Cart oneCart = cartMapper.selectOne(Wrappers.<Cart>lambdaQuery()
                .eq(Cart::getUserId,userId)
                .eq(Cart::getId,dto.getCartId()));

        if (oneCart==null) {
            log.info("未查询到该条购物车");
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        log.info("购物车已存在,修改购物车数量,cart:{}",oneCart);
        if (oneCart.getWaresNumber()==1&&dto.getNewNumber()==-1) {
            log.info("数量不能为0");
            return Result.errorResult(Code.PARAM_INVALID);
        }
        int waresNumber=oneCart.getWaresNumber()+dto.getNewNumber();
        Cart cart=new Cart();
        cart.setCostPrice(oneCart.getCostPrice());
        cart.setWaresNumber(waresNumber);
        int updateCartNum = cartMapper.update(cart,Wrappers.<Cart>lambdaQuery().eq(Cart::getId,dto.getCartId()));
        if (updateCartNum== Message.Check_Int_False) {
            log.info("修改失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("任务完成,总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result delCart(UserCartRemoveDto dto) {
        log.info("用户-删除购物车");
        long start = System.currentTimeMillis();

        if (dto==null||dto.getAllOrOne()==null) {
            log.info("dto为空");
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        boolean remove=false;
        Long userId = BaseContext.getCurrentId();
        if (dto.getAllOrOne().equals("all")) {
            log.info("删除全部购物车数据");
            remove = remove(Wrappers.<Cart>lambdaQuery().eq(Cart::getUserId, userId));

        }else if (dto.getAllOrOne().equals("one")){
            log.info("删除单条购物车数据");
            Cart one = getOne(Wrappers.<Cart>lambdaQuery().eq(Cart::getId, dto.getCartId()));
            if (one==null) {
                log.info("未查询到该购物车");
                return Result.errorResult(Code.DATA_NOT_EXIST);
            }
            if (dto.getCartId()==null&&dto.getAllOrOne().equals("one")) {
                log.info("请传输购物车ID");
                return Result.errorResult(Code.PARAM_REQUIRE);
            }
           remove = remove(Wrappers.<Cart>lambdaQuery().eq(Cart::getId, dto.getCartId()).eq(Cart::getUserId, userId));
        }else {
            log.info("参数错误");
            return Result.errorResult(Code.PARAM_INVALID);
        }
        if (!remove) {
            log.info("删除失败");
            return Result.errorResult(Code.SERVER_ERROR);
        }
        long end = System.currentTimeMillis();
        log.info("删除购物车任务完成,总耗时:{}",(end-start));
        return Result.okResult(Code.SUCCESS);
    }
}
